package ru.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

import java.util.ArrayList;
import java.util.List;

/**
 * Пример аспекта для запуска.
 */
@Aspect
public class AccountAspect {
    private static AccountAspect instance;
    private static List<String> actionsList = new ArrayList<>();

    public static AccountAspect getInstance() {
        if (instance == null) {
            instance = new AccountAspect();
        }

        return instance;
    }

    @Around("execution(* *(..))")
    public Object logTime(ProceedingJoinPoint joinPoint) throws Throwable {
        final long start = System.currentTimeMillis();
        actionsList.add("[AccountAspect.java] Start: " + joinPoint.getSignature());
        final Object proceed = joinPoint.proceed();
        final long executionTime = System.currentTimeMillis() - start;
        actionsList.add("[AccountAspect.java] End: " + joinPoint.getSignature() + " executed in " + executionTime + "ms");
        return proceed;
    }

    @Before("execution(* *(..))")
    public void beforeCallMethod(JoinPoint joinPoint) {
        actionsList.add("[AccountAspect.java] Before: " + joinPoint.toString());
    }

    @After("execution(* *(..))")
    public void afterCallMethod(JoinPoint joinPoint) {
        actionsList.add("[AccountAspect.java] After: " + joinPoint.toString());
    }

    public List<String> getActionsList() {
        return actionsList;
    }

    public void clearList() {
        actionsList.clear();
    }
}
